<template>
  <view class="content">
    <u-form :model="form" ref="form1">
      <u-form-item label="姓名" prop="username" class="username" label-width="auto">
        <u-input v-model="form.username"/>
      </u-form-item>
      <u-form-item label="密码" prop="password" label-width="auto">
        <u-input v-model="form.password" type="password"/>
      </u-form-item>
      <u-form-item label="联系方式" prop="contact" label-width="auto">
        <u-input v-model="form.contact"/>
      </u-form-item>

    </u-form>
    <u-button @click="submit" class="submit">提交</u-button>
    <view class="switch">
      <view @click="toLogin">登录</view>
    </view>
  </view>
</template>

<script>
import {captchaGetApi, userLoginApi, userRegisterApi} from "@/network/api/api";
import {setToken} from "@/common/auth";
import UInput from "@/uni_modules/vk-uview-ui/components/u-input/u-input.vue";
import UButton from "@/uni_modules/vk-uview-ui/components/u-button/u-button.vue";
import UFormItem from "@/uni_modules/vk-uview-ui/components/u-form-item/u-form-item.vue";
import {myThrottle} from "@/common/common";

export default {
  components: {UFormItem, UButton, UInput},
  data() {
    return {
      captcha: '',
      form: {
        password: '',
        username: '',
        contact: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入合法用户名', trigger: ['change', 'blur'], pattern: "^[a-zA-Z0-9]{4,10}$"}],
        password: [
          {required: true, message: '请输入密码', trigger: ['change', 'blur'], pattern: "^[a-zA-Z0-9]{4,10}$"}]
      }
    };
  }
  ,
  onReady() {
    this.$refs.form1.setRules(this.rules);
  }
  , onShow() {
    this.getCaptcha()
  },
  methods: {
    getCaptcha() {
      const _this = this
      console.log("点击1")
      captchaGetApi(this.form).then(res => {
        console.log(res)
        _this.captcha = res.data
      })
    },
    login() {
      const _this = this
      userRegisterApi(this.form).then(res => {
        console.log(res)
        if (res.code === 200) {
          console.log(res)
          setToken(res.data)
          uni.showToast({
            title: res.message,
            icon: 'none'
          });
          _this.toLogin()
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }).catch(err => {
        console.log(err)
      })
    }
    ,
    toLogin() {
      uni.navigateTo(
          {
            url: "/pages/login/login"
          }
      )
    },
    submit() {
      this.$refs.form1.validate((valid) => {
        if (valid) {
          this.login();
        }
      })
    }
  }
}
;
</script>
<style lang="css" scoped>
.content {
  position: absolute;
  width: 100%;
  height: 100%;
}

.username {
  margin-top: 50%;
}

.switch {
  margin-top: 30rpx;
}

.submit {
  margin-top: 10%;
}
</style>